package com.ymk.base.service.impl;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymk.base.exception.MallException;
import com.ymk.base.service.WxService;
import com.ymk.base.utlis.DateUtil;
import com.ymk.base.utlis.ParamsBuilder;

import com.ymk.bo.user.UserInfoBO;
import com.ymk.bo.work.WorkApplyBO;
import com.ymk.bo.work.WorkShareBO;
import com.ymk.core.constants.WxConstants;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;



@Service
public class WxServiceImpl implements WxService {

    private final static Logger logger = LoggerFactory.getLogger(WxServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;
    

    @Override
    public  UserInfoBO getUserPhone(String code) throws Exception {
        UserInfoBO userBO = new UserInfoBO();
        userBO.setReqCode(code);
        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("code", code);
        String resData = HttpUtil.post(WxConstants.WX_GET_USER_PHONE, JSON.toJSONString(params.build()));
        if (StringUtils.isBlank(resData)) {
            logger.error(resData);
            throw new MallException("获取手机号异常");
        }
        logger.info(resData);
        JSONObject param = JSON.parseObject(resData);
        userBO.setRespData(param.toJSONString());
        if (WxConstants.RESPONSE_SUCCESS.equals(param.getString("errmsg"))) {

            userBO.setMobile(param.getJSONObject("phone_info").getString("phoneNumber"));
        }

        return userBO;
    }

    /**
     * @param workShareBO 图片所带信息
     * @param path        文件存储路径
     * @return 云托管文件路径
     */
    @Override
    public String uploadFile(WorkShareBO workShareBO, String path) {
        String scene = "userId=" + workShareBO.getUserId() + "&workId=" + workShareBO.getWorkId();

        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("page", workShareBO.getPage())
                .addParam("scene", scene)
                .addParam("check_path", false);

        byte[] bytes = getWechatQrcodeByRestTemplate(WxConstants.WX_GET_CODE, params.build());

        return uploadFileData(bytes, path);
    }

    /**
     * @param data 文件
     * @param path 文件存储路径
     * @return 云托管文件路径
     */
    @Override
    public String uploadFileData(byte[] data, String path) {
        {

            ParamsBuilder params = ParamsBuilder.newBuild()
                    .addParam("env", WxConstants.X_WX_ENV)
                    .addParam("path", path);
            // 获取上传文件链接
            String resData = HttpUtil.post(WxConstants.WX_UPLOAD, JSON.toJSONString(params.build()));
            JSONObject json = JSON.parseObject(resData);

            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("key", path);
            map.add("Signature", json.getString("authorization"));
            map.add("x-cos-security-token", json.getString("token"));
            map.add("x-cos-meta-fileid", json.getString("cos_file_id"));
            map.add("file", data);

            //上传文件
            doPostFormData(json.getString("url"), map);
            return json.getString("file_id");
        }
    }

    /**
     * 上传文件
     *
     * @param url
     * @param data
     */

    public void doPostFormData(String url, MultiValueMap<String, Object> data) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //头部类型
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            //构造实体对象
            HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(data, headers);
            //发起请求,服务地址，请求参数，返回消息体的数据类型
            ResponseEntity<String> response = restTemplate.postForEntity(url, param, String.class);
        } catch (Exception ex) {
            logger.error("doPostFormData", ex);
        }


    }

    /**
     * 获取生产小程序码的图片二进制并转成 byte[]
     *
     * @param url
     * @param body
     * @return
     */

    public byte[] getWechatQrcodeByRestTemplate(String url, Map<String, Object> body) {
        {
            return restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(body, null), byte[].class).getBody();
        }
    }

    @Override
    public JSONObject idCardOCR(String fileId) throws Exception {
        try {
            String url = this.getDownLoadUrl(fileId);
            String result = restTemplate.postForObject(WxConstants.ID_CARD + "?img_url=" + url, null, String.class);
            logger.info(result);
            JSONObject param = JSON.parseObject(result);
            if (!WxConstants.RESPONSE_SUCCESS.equals(param.getString("errmsg"))){
                throw new MallException("实名认证异常");
            }
            return param;
        }catch (Exception e){
            throw new MallException("实名认证异常");
        }
    }

    @Override
    public String getDownLoadUrl(String fileId) throws Exception {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileid",fileId);
        jsonObject.put("max_age",0);
        jsonArray.add(jsonObject);

        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("env", WxConstants.X_WX_ENV)
                .addParam("file_list", jsonArray);
        String resData = HttpUtil.post(WxConstants.DOWN_FILE, JSON.toJSONString(params.build()));
        JSONObject param = JSON.parseObject(resData);
        if (StringUtils.isBlank(resData) || !WxConstants.RESPONSE_SUCCESS.equals(param.getString("errmsg"))) {
            logger.error(resData);
            throw new MallException("获取文件信息异常");
        }
        logger.info(resData);
        return param.getJSONArray("file_list").getJSONObject(0).getString("download_url");

    }

    /**
     * 发送订阅消息
     * @param workApplyBO
     * @param userInfoBOS
     * @throws Exception
     */
    @Override
    public void sendMessage(WorkApplyBO workApplyBO, List<UserInfoBO> userInfoBOS) throws Exception {



        ParamsBuilder thing1 = ParamsBuilder.newBuild()
                .addParam("value",workApplyBO.getName());
        ParamsBuilder time2 = ParamsBuilder.newBuild()
                .addParam("value", DateUtil.dateToString(workApplyBO.getCreatedDate(),"yyyy年MM月dd日 HH:mm"));
        ParamsBuilder thing3 = ParamsBuilder.newBuild()
                .addParam("value",workApplyBO.getContent());
        ParamsBuilder phone_number4 = ParamsBuilder.newBuild()
                .addParam("value",workApplyBO.getMobile());

        ParamsBuilder data = ParamsBuilder.newBuild()
                .addParam("thing1",thing1.build())
                .addParam("time2",time2.build())
                .addParam("thing3",thing3.build())
                .addParam("phone_number4",phone_number4.build());

        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("template_id", WxConstants.APPLY_TEMPLATE_ID)
                .addParam("data",data.build());


        for (UserInfoBO userInfoBO : userInfoBOS) {
            if(!StringUtils.isBlank(userInfoBO.getWxOpenId())){
                params.addParam("touser", userInfoBO.getWxOpenId());
                String resData = HttpUtil.post(WxConstants.SEND_MESSAGE, JSON.toJSONString(params.build()));
                JSONObject param = JSON.parseObject(resData);
                logger.info(param.toString());
            }


        }

    }

    public static void main(String[] args) throws Exception {

//        Date date = new Date();
//        System.out.println(DateUtil.dateToString(date,"yyyy年MM月dd日 HH:mm"));

        // 获取openid
//        String url = "https://api.weixin.qq.com/sns/jscode2session";
//        String code = "0b1RRyFa1ezGQF0R4FHa1ZNFly3RRyFu";
//        String send = url +"?appid="+WxConstants.APP_ID+"&secret="+WxConstants.APP_SECRET+"&js_code="+code+"&grant_type=authorization_code";
//        String resData = HttpUtil.get(send);
//        JSONObject param = JSON.parseObject(resData);
//        System.out.println(resData);
//        System.out.println(param.getString("openid"));
//        String openid = "odd5q5alNV2_IC2ZrruzFipCbwkw";

        // 获取token
       String url = "https://api.weixin.qq.com/cgi-bin/token";
       String send = url+"?grant_type=client_credential&appid="+WxConstants.APP_ID+"&secret="+WxConstants.APP_SECRET;
        String resData = HttpUtil.get(send);
        System.out.println(resData);
       String token = "72_Kh02owB2J2JqUxOCztsRhghyGqmSEYqxUEXGH45NoRt8i7U7upyUoDRAFZK1mTDmbCF9_qCqhl0f_y1_Kc6eHZ0cRML-n6FxtMtfLlJnMLBTsld_jjmDb8NBY2ITOOeADAPKK";

        // 获取手机号
//        WxServiceImpl wxService = new WxServiceImpl();
////        String code = "3da480ac8fb60f9202dd00cf2dca2e0b44d2213b80bd3c920d1d14580881e39c";
////        UserInfoBO userPhone = wxService.getUserPhone(code);
////        System.out.println(userPhone.toString());



        // 获取文件下载链接
//        String url = WxConstants.DOWN_FILE+"?access_token="+token;
//
//        JSONArray jsonArray = new JSONArray();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("fileid","cloud://dev-9gjsl77taaa6cab5.6465-dev-9gjsl77taaa6cab5-1318959325/idcard/6b0b379b89bc7bad4fbd596ca3624c2.jpg");
//        jsonObject.put("max_age",0);
//        jsonArray.add(jsonObject);
//
//        ParamsBuilder params = ParamsBuilder.newBuild()
//                .addParam("env", WxConstants.X_WX_ENV)
//                .addParam("file_list", jsonArray);
//        String resData = HttpUtil.post(url, JSON.toJSONString(params.build()));
//        JSONObject param = JSON.parseObject(resData);
//        String down = param.getJSONArray("file_list").getJSONObject(0).getString("download_url");
//        System.out.println(down);


        // 实名认证
//        RestTemplate restTemplate = new RestTemplate();
//        String img_url = "https://6465-dev-9gjsl77taaa6cab5-1318959325.tcb.qcloud.la/idcard/6b0b379b89bc7bad4fbd596ca3624c2.jpg?sign=12d2e1642d81276469ea7c965d9ae9b9&t=1691659890";
//        String img = "https://6465-dev-9gjsl77taaa6cab5-1318959325.tcb.qcloud.la/idcard/12c088d4ffc08bb79cab98c0ad426bb.jpg?sign=b9212ddc74920795a2163417b6131c58&t=1691661602";

//        String url = "https://api.weixin.qq.com/cv/ocr/idcard?access_token="+token+"&img_url="+img;
//
//        ParamsBuilder params = ParamsBuilder.newBuild()
//                .addParam("img_url", img_url);
//        String result = HttpUtil.post(url, "");
       // String result = restTemplate.postForObject(url,null,String.class);
      //  System.out.println(result);
// {"errcode":0,"errmsg":"ok","type":"Front","name":"韩紫云","id":"130682199803113170","addr":"河北省定州市邢邑镇西阳木村7队1005号","gender":"男","nationality":"汉","birth":"1998-03-11","card_property":4}
// {"errcode":0,"errmsg":"ok","type":"Back","valid_date":"20200317-20300317","authority":"定州市公安局","card_property":4}

          // 腾讯发短信
//        try{
//            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
//            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
//            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
//            Credential cred = new Credential("SecretId", "SecretKey");
//            // 实例化一个http选项，可选的，没有特殊需求可以跳过
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("sms.tencentcloudapi.com");
//            // 实例化一个client选项，可选的，没有特殊需求可以跳过
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//            // 实例化要请求产品的client对象,clientProfile是可选的
//            SmsClient client = new SmsClient(cred, "", clientProfile);
//            // 实例化一个请求对象,每个接口都会对应一个request对象
//            SendSmsRequest req = new SendSmsRequest();
//            String[] phoneNumberSet1 = {"123"};
//            req.setPhoneNumberSet(phoneNumberSet1);
//
//            req.setSmsSdkAppId("44");
//            req.setSignName("55");
//            req.setTemplateId("5566");
//
//            String[] templateParamSet1 = {"4324"};
//            req.setTemplateParamSet(templateParamSet1);
//
//            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
//            SendSmsResponse resp = client.SendSms(req);
//            // 输出json格式的字符串回包
//            System.out.println(SendSmsResponse.toJsonString(resp));
//        } catch (TencentCloudSDKException e) {
//            System.out.println(e.toString());
//        }



    }


}
